<template>
  <basic-container>
    <el-tabs v-model="activeName" style="margin: 0 10px" @tab-click="handleClick">
      <el-tab-pane label="外部序列号" name="outSn"></el-tab-pane>
      <el-tab-pane label="外部包装条码" name="outPackSN"></el-tab-pane>
      <el-tab-pane label="预生成序列号" name="regeneratedSN"></el-tab-pane>
    </el-tabs>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :search.sync="query"
      :permission="permissionList"
      ref="crud"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport">导入</el-button>
        <el-button icon="el-icon-delete" size="small" type="danger" @click.stop="handleDelete">删除 </el-button>
      </template>
      <template slot-scope="" slot="sequenceDefinitionCodeSearch">
        <el-input placeholder="请选择 序列号规则代码" v-model="query.sequenceDefinitionCode">
          <el-button slot="append" icon="el-icon-search" @click="openSequenceDefinitionModal('search')"></el-button>
        </el-input>
      </template>
    </avue-crud>
    <out-sn-import ref="outSnImport" :import-type="activeName" :showImportDialog="showImportDialog" @closeImportDialog="closeImportDialog"></out-sn-import>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import outSnImport from '@/views/product/components/outSnImport';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import { columnMap } from '@/views/product/refactor/barcodeimport';
import { getOutList, getOutPackingList, getList, outPackSnRemove, regeneratedSnRemove, outSnRemove } from '@/api/product/barcodeImport';
import { CancelToken } from 'axios';
export default {
  name: 'barcodeimport',
  components: {
    userTableConfig,
    CommonModalTemplate,
    outSnImport
  },
  mixins: [userConfig()],
  data() {
    return {
      cancel: null,
      printInfoModel: false,
      form: {},
      query: {},
      // printTitle: '',
      loading: true,
      tableOption: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      showImportDialog: false,
      modalTitle: '',
      data: [],
      activeName: 'outSn',
      selectionList: [],
      option: {
        height: 'calc(100vh - 416px)',
        calcHeight: 30,
        tip: false,
        menu: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        indexLabel: '序号',
        selection: true,
        searchLabelWidth: 150,
        columnBtn: false,
        column: []
      }
    };
  },
  mounted() {
    const column = columnMap[this.activeName];
    this.$set(this.option, 'column', column);
    //this.getDefaultPrinter();
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission', 'userInfo']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission, false),
        viewBtn: this.vaildData(this.permission, false),
        delBtn: this.vaildData(this.permission, false),
        editBtn: this.vaildData(this.permission, false)
      };
    },
    deleteData() {
      if (this.activeName === 'outSn') {
        return this.selectionList.map((i) => i.sequenceNumber);
      } else if (this.activeName === 'outPackSN') {
        return this.selectionList.map((i) => {
          return {
            workOrderNo: i.workOrderNo,
            outerPackingSn: i.outerPackingSn
          };
        });
      } else {
        return this.selectionList.map((i) => i.id).join(',');
      }
    }
  },
  methods: {
    rowDel(row) {},
    searchReset() {
      this.query = {};
      if (this.activeName === 'regeneratedSN' && !this.query.sequenceDefinitionCode) {
        this.$message({
          type: 'warning',
          message: '请输入序列号规则编码进行查询！'
        });
        this.page.total = 0;
        this.data = [];
        return;
      }
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      if (this.activeName === 'regeneratedSN' && !this.query.sequenceDefinitionCode) {
        this.$message({
          type: 'warning',
          message: '请输入序列号规则编码进行查询！'
        });
        this.page.total = 0;
        this.data = [];
        done();
        return;
      }
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud && this.$refs.crud.toggleSelection();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    handleCancelRequest() {
      this.cancel('取消请求');
    },
    async handleClick() {
      this.query = {};
      this.data = [];
      const column = columnMap[this.activeName];
      this.$set(this.option, 'column', column);
      this.handleCancelRequest();
      this.onLoad(this.page);
      this.$nextTick(() => {
        this.$structuralSplit();
      });
    },
    handleImport() {
      this.showImportDialog = true;
    },
    handleDelete() {
      if (this.selectionList.length) {
        this.$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            const removeInterfaceMap = { outSn: outSnRemove, outPackSN: outPackSnRemove, regeneratedSN: regeneratedSnRemove };
            return removeInterfaceMap[this.activeName](this.deleteData);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.selectionClear();
          });
      }
    },
    closeImportDialog() {
      this.showImportDialog = false;
      this.onLoad(this.page);
    },
    async onLoad(page, params = {}) {
      const interfaceMap = { outSn: getOutList, outPackSN: getOutPackingList, regeneratedSN: getList };
      this.loading = true;
      try {
        if (this.activeName === 'regeneratedSN' && !this.query.sequenceDefinitionCode) {
          this.data = [];
          return;
        }
        const res = await interfaceMap[this.activeName](
          { cancelToken: new CancelToken((c) => (this.cancel = c)) },
          page.currentPage,
          page.pageSize,
          Object.assign(params, this.query)
        );
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
        this.selectionClear();
      }
    },
    getSelectedRows(rowData) {
      this.$set(this.query, 'sequenceDefinitionCode', rowData.code || '');
    },
    openSequenceDefinitionModal(type) {
      this.modalTitle = type;
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page?isPregenerated=true&type=material&subType=work_in_progress',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat'
          }
        ]
      };
    }
  }
};
</script>
<style lang="scss" scoped></style>
